package com.aqie.easy.hash;

import java.util.HashMap;
import java.util.Map;

/**
 * @Function: 136. 只出现一次的数字
 * @Author: aqie
 * @Date: 2019/6/30 10:22
 * map 遍历四种方法
 * 1. foreach map.entrySet 遍历 Map.Entry
 *  + for (Map.Entry<String, String> entry : map.entrySet())
 * 2. foreach map.entrySet 遍历 key value
 *  + for (String key : map.keySet())
 * 3. Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
 * 4. 根据key 找value 效率低, for (String v : map.values())
 */
public class SingleNumber {
    public int singleNumber(int[] nums) {
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num, map.getOrDefault(num, 0) + 1);
        }


        for (Map.Entry<Integer, Integer> entry : map.entrySet()){
            if (entry.getValue() == 1){
                return entry.getKey();
            }
        }
        return -1;
    }

    public int singleNumber2(int[] nums) {
        if (nums.length == 0) return -1;
        int ans = nums[0];
        for (int i = 1; i < nums.length; i++){
            ans ^= nums[i];
        }
        return ans;
    }
}
